package com.qf.openapi.web.master.filter;

import com.qf.openapi.web.master.vo.ReturnVo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

//@WebFilter("/*")
public class CurrencyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("=======================================");
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
        HttpServletRequest req = (HttpServletRequest) request;
        
        ReturnVo r = new ReturnVo();
    
        String reqHeaderKey;
    
        String str;
    
        HashMap<String, Object> headers = new HashMap<>();
        HashMap<String, Object> body = new HashMap<>();
    
        Enumeration<String> reqHeaderNames = req.getHeaderNames();
        while (reqHeaderNames.hasMoreElements()){
            reqHeaderKey = reqHeaderNames.nextElement();
            headers.put(reqHeaderKey, req.getHeader(reqHeaderKey));
            r.setHeaders(headers);
        }
    
        /*try {
            BufferedReader br = req.getReader();
        
            while ((str = br.readLine()) != null){
                for (String s : str.split("&")) {
                    String[] split = s.split("=");
                    if (split.length > 1){
                        body.put(split[0], split[1]);
                    }
                }
            }
        
            r.setBody(body);
        
        
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
    
        Map<String, String[]> parameterMap = req.getParameterMap();
    
        r.setParam(parameterMap);
    
        System.out.println(r);
    
        chain.doFilter(req, response);
    }
    
    @Override
    public void destroy() {
        System.out.println("=======================================");
    }
}
